package com.neusoft.elmboot.service.impl;

import java.util.ArrayList;
import java.util.List;

import com.neusoft.elmboot.mapper.BusinessMapper;
import com.neusoft.elmboot.po.*;
import com.neusoft.elmboot.service.ScoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.neusoft.elmboot.mapper.CartMapper;
import com.neusoft.elmboot.mapper.OrderDetailetMapper;
import com.neusoft.elmboot.mapper.OrdersMapper;
import com.neusoft.elmboot.service.OrdersService;
import com.neusoft.elmboot.util.CommonUtil;

@Service
public class OrdersServiceImpl implements OrdersService{
	
	@Autowired
	private CartMapper cartMapper;
	@Autowired
	private OrdersMapper ordersMapper;
	@Autowired
	private OrderDetailetMapper orderDetailetMapper;

	@Autowired
	private BusinessMapper businessMapper;

	@Autowired
	private ScoreService scoreService;  // 注入 ScoreService


	@Override
	@Transactional
	public int createOrders(Orders orders, List<OrderDetailet> orderItems) {
		// 1. 查询当前用户购物车中当前商家的所有食品
		Cart cart = new Cart();
		cart.setUserId(orders.getUserId());
		cart.setBusinessId(orders.getBusinessId());
		List<Cart> cartList = cartMapper.listCart(cart);

		// 2. 创建订单（返回生成的订单编号）
		orders.setOrderDate(CommonUtil.getCurrentDate());
		ordersMapper.saveOrders(orders);
		int orderId = orders.getOrderId();

		// 3. 如果提供了 orderItems 列表，直接使用该列表保存订单明细
		List<OrderDetailet> list = new ArrayList<>();
		if (orderItems != null && !orderItems.isEmpty()) {
			for (OrderDetailet od : orderItems) {
				od.setOrderId(orderId); // 关联订单ID
				list.add(od);
			}
		} else {
			// 如果没有提供 orderItems，则默认从购物车创建订单明细
			for (Cart c : cartList) {
				OrderDetailet od = new OrderDetailet();
				od.setOrderId(orderId);
				od.setFoodId(c.getFoodId());
				od.setQuantity(c.getQuantity());
				list.add(od);
			}
		}

		// 4. 批量保存订单明细
		orderDetailetMapper.saveOrderDetailetBatch(list);

		// 5. 从购物车表中删除相关食品信息
		cartMapper.removeCart(cart);

		return orderId;
	}


	@Override
	public Orders getOrdersById(Integer orderId) throws Exception {
		// 查询订单时加载关联的商家信息和订单详情
		Orders order = ordersMapper.getOrdersById(orderId);

		if (order != null) {
			// 查询并设置商家信息
			Business business = businessMapper.getBusinessById(order.getBusinessId());
			order.setBusiness(business);

			// 查询并设置订单明细
			List<OrderDetailet> orderDetails = orderDetailetMapper.listOrderDetailetByOrderId(orderId);
			order.setList(orderDetails);
		}

		return order;
	}


	@Override
	public List<Orders> listOrdersByUserId(String userId){
		return ordersMapper.listOrdersByUserId(userId);
	}

	@Override
	@Transactional
	public boolean updateOrderState(Long orderId, Integer orderState, Integer usedScore) {
		// 先更新订单状态
		int updatedRows = ordersMapper.updateOrderState(orderId, orderState);

		if (updatedRows > 0) {
			// 如果使用了积分，调用 useScore 扣除积分
			if (usedScore > 0) {
				scoreService.useScore(Math.toIntExact(orderId), usedScore);
			} else {
				// 如果没有使用积分，按照 1元=1积分 计算新增积分
				Orders order = ordersMapper.getOrdersById(Math.toIntExact(orderId));  // 获取订单信息
				Double newScore = order.getOrderTotal();   // 1元=10积分
				if (newScore > 0) {
					// 创建新的积分记录
					Score score = new Score();
					score.setUserId(order.getUserId());
					score.setOrderId(Math.toIntExact(orderId));
					score.setScoreCount(newScore);  // 积分数量
					scoreService.createScore(score);  // 保存到数据库
				}
			}
			return true;
		}
		return false;
	}

}
